package com.gusha.service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gusha.dao.SysMailingDao;
import com.gusha.model.ReceivingAddress;
import com.gusha.model.SysArea;
import com.gusha.model.SysMailing;
import com.gusha.model.SysRepository;
import com.gusha.utils.JsonResult;

@Service
@Transactional
public class SysMailingService {
	@Autowired
    private SysMailingDao sysMailingDao;
	
    public Page<SysMailing> findAll(Pageable pageable, SysMailing sysMailing) {
    	
        @SuppressWarnings("serial")
        Page<SysMailing> result= sysMailingDao.findAll(new Specification<SysMailing>() {
            @Override
            public Predicate toPredicate(Root<SysMailing> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (sysMailing.getId() != null) {
                    list.add(cb.equal(root.get("id").as(BigInteger.class),sysMailing.getId()));
                }
                if (sysMailing.getSysRepository() != null) {
                    list.add(cb.equal(root.get("sysRepository").as(SysRepository.class),sysMailing.getSysRepository()));
                }
                if (sysMailing.getReceivingAddress() != null) {
                    list.add(cb.equal(root.get("receivingAddress").as(ReceivingAddress.class),sysMailing.getReceivingAddress()));
                }
                if (sysMailing.getState()!=null) {
                    list.add(cb.equal(root.get("state").as(BigInteger.class),sysMailing.getState()));
                }
                
                if (sysMailing.getIsDelete() != null) {
                    list.add(cb.equal(root.get("isDelete").as(BigInteger.class),sysMailing.getIsDelete()));
                }
                if (sysMailing.getIsCheck() != null) {
                    list.add(cb.equal(root.get("isCheck").as(BigInteger.class),sysMailing.getIsCheck()));
                }
                if (sysMailing.getAddTime() != null) {
                    list.add(cb.equal(root.get("addTime").as(Date.class),sysMailing.getAddTime()));
                }
                
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        },pageable);
         return result;
    }

	
}
